package com.example.vault;

import com.example.vault.entity.Person;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.core.VaultSysOperations;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.core.VaultTransitOperations;
import org.springframework.vault.support.VaultMount;
import org.springframework.vault.support.VaultResponseSupport;

public class VaultApp {

    public static void main(String[] args) {

        //创建vault对象，TokenAuthentication配置为运行此应用程序的根令牌
        VaultEndpoint vaultEndpoint = VaultEndpoint.create("127.0.0.1", 8200);
        //设置http访问，https需要认证文件
        vaultEndpoint.setScheme("http");
        VaultTemplate vaultTemplate = new VaultTemplate(vaultEndpoint, new TokenAuthentication("s.FaKngpds8M1dlo2zV8lKWDiG"));

        Person secrets = new Person();
        secrets.setName("hello");
        secrets.setPassword("world");
        //写入数据到vault中secret/myapp 目录
        vaultTemplate.write("kv/myapp", secrets);

        //查询secret/myapp目录下数据
        VaultResponseSupport<Person> response = vaultTemplate.read("kv/myapp", Person.class);
        System.out.println(response.getData().getName());

        //删除数据
//        vaultTemplate.delete("secret/myapp");


        //  Let's encrypt some data using the Transit backend.
        VaultTransitOperations transitOperations = vaultTemplate.opsForTransit();

        // We need to setup transit first (assuming you didn't set up it yet).
        VaultSysOperations sysOperations = vaultTemplate.opsForSys();
        if (!sysOperations.getMounts().containsKey("transit/")) {
            sysOperations.mount("transit", VaultMount.create("transit"));
            transitOperations.createKey("foo-key");
        }

        // Encrypt a plain-text value
        String ciphertext = transitOperations.encrypt("foo-key", "测试加密解密");
        System.out.println("Encrypted value");
        System.out.println("-------------------------------");
        System.out.println(ciphertext);
        System.out.println("-------------------------------");
        System.out.println();

        // Decrypt
        String plaintext = transitOperations.decrypt("foo-key", ciphertext);
        System.out.println("Decrypted value");
        System.out.println("-------------------------------");
        System.out.println(plaintext);
        System.out.println("-------------------------------");
        System.out.println();
    }
}